#/usr/bin/python
# -*- encoding=UTF-8 -*-

import os
import re
import sys
import yaml

import config

SESSION_LIST_FILE = '__FolderData__.ini'

def get_info(path, rnc_type, session):
    rnc_ini =  os.path.join(path, rnc_type, session + '.ini')
    tester_ini = os.path.join(path, rnc_type, session + '_Tester.ini')

    info = config.TestEnvInfo(rnc_type, session)
    if rnc_type == "cRNC":
        info.rnc.username = "SYSTEM"
        info.rnc.password = "SYSTEM"
    else:
        info.rnc.username = "root"
        info.rnc.password = "root"
    info.rnc.hostname = get_ip(rnc_ini)
    
    info.tester.hostname = get_ip(tester_ini)
    info.tester.username = "guest"
    info.tester.password = "guest1"
    info.ets = "/data/user/wulinbo/tad/ets"
    return info

def get_ip(file_name):
    ip = None
    if os.path.isfile(file_name):
        with open(file_name, 'r') as outfile:
            for line in outfile:
                if '\"Hostname\"' in line:
                    ip = (line.split('=')[1]).strip()
                    break
    return ip

def read_crt_conf(file_name, section):
    option = None
    if os.path.isfile(file_name):
        with open(file_name, 'r') as outfile:
            for line in outfile:
                if section in line:
                    option = (line.split('=')[1]).strip()
    return option

def export_crt(path, conf=None):
    exist_rnc = []
    if conf is None:
        conf = []
    else:
        for info in conf:
            exist_rnc.append(info.name)
    prog = re.compile(r"[mcADRNC]+_\d{2}[A]?$")
    for rnc_type in config.RNC_TYPE:
            ini_file = os.path.join(path, rnc_type, SESSION_LIST_FILE)
            session_list = read_crt_conf(ini_file, 'Session List')
            if session_list:
                session_lists = session_list.split(':')
                session_lists.sort(key=str.lower)
                for session in session_lists:
                    if prog.match(session) and session not in exist_rnc:
                        info = get_info(path, rnc_type, session)
                        if info:
                            conf.append(info)
    return conf

def combine_yaml(old_file=None):
    new_file = 'new_rnclist.yaml'
    old_yaml = []
    if old_file and os.path.isfile(old_file):
        with open(old_file, 'r') as outfile:
            for data in yaml.load_all(outfile):
                old_yaml.append(data)


    session_path = 'D:\\Downloads\\SecureCRT\\SecureCRT_Config\\Sessions'
    new_yaml = export_crt(session_path, old_yaml)

    with open(new_file, 'w') as outfile:
        yaml.dump_all(new_yaml, outfile, default_flow_style=False, 
                      explicit_start=True)

if __name__ == '__main__':
    yaml_file = None
    if len(sys.argv) > 1:
        yaml_file = sys.argv[1]
    combine_yaml(yaml_file)